import service from "@/api/service";

export default {
  namespaced: true,
  state: {
    appId: "sys",
    queryObject: {
      pageIndex: 1,
      pageSize: 20,
      sortFields: {
        CreateTime: true,
      },
      parameters: {
        keyword: "",
      },
    },
    dataTable: {
      result: [],
      pageIndex: 1,
      pageSize: 20,
      pageCount: 0,
      rowCount: 0,
    }
  },
  mutations: {
    setData(state, data) {
      state.dataTable = data;
    },
    setParameters(state, parameters) {
      for (let name in parameters) {
        state.queryObject.parameters[name] = parameters[name];
      }
    },
    setAppId(state, appId){
      state.appId = appId;
    }
  },
  actions: {
    query({ commit, state }) {
      return service.dict
        .query({ routeData: { appId: state.appId }, data: state.queryObject })
        .then((response) => {
          commit("setData", response.success ? response.data : null);
          return response;
        })
        .catch((error) => {
          return error;
        });
    },
    item({ commit }, name) {
      return service.dict
        .item({ routeData: { appId: state.appId },  params: { name } })
        .then((response) => {
          return response;
        })
        .catch((error) => {
          return error;
        });
    },
    create({ commit, state }, item) {
      return service.dict
        .create({ routeData: { appId: state.appId },  data: item })
        .then(r => {
          if (r.success)
            return dispatch("query");
        })
        .catch((error) => {
          return error;
        });
    },
    update({ commit, state }, item) {
      return service.dict
        .update({ routeData: { appId: state.appId },  data: item })
        .then(r => {
          return dispatch("query");
        })
        .catch((error) => {
          return error;
        });
    },
    delete({ dispatch, state }, ids) {
      return service.dict
        .remove({ routeData: { appId: state.appId },  data: ids })
        .then((response) => {
          if (response.success) {
            return dispatch("query");
          } else {
            throw response.message;
          }
        })
        .catch((error) => {
          return error;
        });
    },
    toggle({ dispatch, state }, item) {
      return service.dict
        .toggle({ routeData: { appId: state.appId },  params: item })
        .then((response) => {
          if (response.success) {
            return response;
          } else {
            throw response.message;
          }
        })
        .catch((error) => {
          return error;
        });
    }
  },
};
